// 该文件是作用是自动获取本地的ip地址，生成.env文件

import os from 'os'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

// 获取当前文件路径和目录，ESM环境下必须这样写
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

function getLocalIP() {
  const interfaces = os.networkInterfaces()
  for (const iface of Object.values(interfaces)) {
    for (const config of iface) {
      if (config.family === 'IPv4' && !config.internal) {
        return config.address
      }
    }
  }
  return '127.0.0.1'
}

const ip = getLocalIP()
const envPath = path.resolve(__dirname, '.env')
const envContent = `VITE_API_URL=http://${ip}:8000/api\nVITE_TITLE=宏图士的网站\n`

fs.writeFileSync(envPath, envContent)
console.log(`文件.env 已更新为本地 IP: ${ip}`)
